import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'bean.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '消息、事件、方法通道'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int selectedIndex = 0;
  List<Map<String, dynamic>>? musics = [];
  int _counter = 0;
  String? _message;
  bool status = false;
  // ///消息通道
  // static const _channel1 = BasicMessageChannel("messageChanel", StringCodec());
  // ///事件通道
  // static const _channel2 = EventChannel("eventChanel");
  ///方法通道
  static const _channel3 = MethodChannel("methodChannel");

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    ///消息通道消息线程
    // _channel1.setMessageHandler((message) async{
    //   print('消息通道: receive message: $message');
    //   setState(() {
    //     _message = message;
    //   });
    //   return '消息通道: ACK from dart';
    // });
    // ///事件通道接收广播流监听
    // _channel2.receiveBroadcastStream().listen((event) {
    //     print("事件通道: Receive event: $event");
    //     setState(() {
    //       _message = event;
    //     });
    // },onError: (error){
    //   print("事件通道: Receive error: $error");
    // },cancelOnError: true);
    initMusics();
  }

  ///获取音乐
  Future<void> initMusics() async {
    print("initMusics");
    List<dynamic> list = [];
    await Future.delayed(Duration(seconds: 1), () async {
      var result = await _channel3.invokeMethod('initMusics');
      print("初始化返回result: ${result}");
      try {
        list = result as List<dynamic>;
      } catch (e) {
        print("获取异常");
      }
    });

    List<Map<String, dynamic>> list2 = list.map((element) {
      Map<String, dynamic> pigeonMap = {};
      final Map<Object?, Object?> e = element as Map<Object?, Object?>;
      pigeonMap["musicFileUrl"] = e["musicFileUrl"];
      pigeonMap["musicTitle"] = e["musicTitle"];
      pigeonMap["musicUrl"] = e["musicUrl"];
      pigeonMap["musicId"] = e["musicId"];
      pigeonMap["musicDuration"] = e["musicDuration"];
      pigeonMap["musicFileName"] = e["musicFileName"];
      pigeonMap["musicAuthor"] = e["musicAuthor"];
      return pigeonMap;
    }).toList();

    print("获取音乐 result list: $list");
    print("获取音乐 result list2: $list2");
    setState(() {
      musics = list2;
    });
  }

  ///播放
  Future<void> playMusic(int index) async {
    setState(() {
      status = true;
    });
    var result = await _channel3.invokeMethod('playMusic', {"index": index});
    print("播放 result: $result");
  }

  ///开始或继续
  Future<void> startMusic() async {
    setState(() {
      status = !status;
    });
    var result = await _channel3.invokeMethod('startMusic');
    print("开始或继续 result: $result");
  }

  ///停止(结束)
  Future<void> stopMusic() async {
    setState(() {
      status = false;
    });
    var result = await _channel3.invokeMethod('stopMusic');
    print("停止(结束) result: $result");
  }

  ///上一首
  Future<void> lastClick() async {
    setState(() {
      status = true;
      selectedIndex--;
      if (selectedIndex < 0) {
        selectedIndex = musics!.length;
      }
    });
    var result = await _channel3.invokeMethod('lastClick');
    print("上一首 result: $result");
  }

  ///下一首
  Future<void> nextClick() async {
    setState(() {
      status = true;
      selectedIndex++;
      if (selectedIndex > musics!.length) {
        selectedIndex = 0;
      }
    });
    var result = await _channel3.invokeMethod('nextClick');
    print("下一首 result: $result");
  }

  ///播放方法通道
  methodChannel() async {
    var result = await _channel3.invokeMethod('getFlutterInfo');
    print("播放通道: Method invoke result: $result");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Music player"),
        backgroundColor: Colors.blueGrey,
        actions: [
          GestureDetector(
              onTap: () {
                initMusics();
              },
              child: const Icon(Icons.refresh)),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            gradient: const LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Colors.white,
                ])),
        child: Column(
          children: [
            // Text("musics: ${musics}")
            Expanded(
              child: musics!.isEmpty
                  ? SizedBox()
                  : Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 8),
                      child: ListView.separated(
                          itemCount: musics!.length,
                          separatorBuilder: (BuildContext context, int index) {
                            return const Divider();
                          },
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              decoration: BoxDecoration(
                                color: selectedIndex == index
                                    ? Colors.blueGrey
                                    : Colors.black12,
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: ListTile(
                                  onTap: () {
                                    setState(() {
                                      selectedIndex = index;
                                      playMusic(index);
                                    });
                                  },
                                  shape: const CircleBorder(),
                                  selected: selectedIndex == index,
                                  selectedColor: Colors.blue,
                                  style: ListTileStyle.list,
                                  title: Text(
                                    musics?[index]["musicFileName"],
                                    style: TextStyle(
                                        color: selectedIndex == index
                                            ? Colors.white
                                            : Colors.black),
                                  ),
                                  subtitle: Text(
                                    musics?[index]["musicAuthor"],
                                    style: TextStyle(
                                        color: selectedIndex == index
                                            ? Colors.white
                                            : Colors.black),
                                  ),
                                  // trailing: selectedIndex == index?Icon(Icons.check_box,color: Colors.blue,):Icon(Icons.check_box_outline_blank,color: Colors.grey,),
                                ),
                              ),
                            );
                          }),
                    ),
            ),
            Container(
              color: Colors.blueGrey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                margin:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                height: 75,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    gradient: const LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          Colors.white,
                          Colors.white,
                        ])),
                child: Material(
                  color: Colors.transparent,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Text("sdf${musics?.length}",style: TextStyle(color: Colors.red),),
                      Expanded(
                        child: musics!.length <= 0
                            ? SizedBox()
                            : Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    musics?[selectedIndex]["musicFileName"],
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 1,
                                  ),
                                  Text(
                                    musics?[selectedIndex]["musicAuthor"],
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 1,
                                    style: const TextStyle(fontSize: 10),
                                  ),
                                ],
                              ),
                      ),
                      InkWell(
                          onTap: () {
                            lastClick();
                          },
                          child: const Icon(
                            Icons.skip_previous,
                            size: 35,
                          )),
                      InkWell(
                          onTap: () {
                            startMusic();
                          },
                          child: Icon(
                            !status ? Icons.play_arrow : Icons.stop,
                            size: 35,
                          )),
                      InkWell(
                          onTap: () {
                            nextClick();
                          },
                          child: const Icon(
                            Icons.skip_next,
                            size: 35,
                          )),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
